<template>
  <div style="width:90%;margin:10px auto 0">
    <!-- pdf -->
    <!-- <iframe :src="pdfUrl" width="100%" height="775px" v-if="pdfShow"></iframe>  -->
    <!-- <shukeOfd v-if="pdfShow" :infoItem="infoItem"></shukeOfd> -->
    <!--1.pdf 2.ofd 3.word 4.xls 5.mp4 6.mp3  7.jpg png  -->
    <div style="width:100%;margin:0 auto" v-if="itemList.DOC_FILE_TYPE == 'PDF'">
      <p v-if="isText != ''">{{ isText }}</p>
      <iframe width="100%" height="775px" id="pdfContainer" :src="pdfUrl" frameborder="0" v-if="isUrl && pdfUrl"
        :style="istype == '1' ? 'height:740px' : 'height:790px'">
      </iframe>
      <!-- <pdfDemo :url="pdfUrl" :item="item" :istype="istype" :source="source" v-if="isUrl && pdfUrl">
        </pdfDemo> -->
      <!--  -->
      <div style="position: relative;overflow: hidden;background:#dfe6ec;widht:100%"
        :style="istype == '1' ? 'height:740px' : 'height: 790px'" v-else>

        <imgViever v-if="imgList.length > 0" :imgList="imgList" :listLength="imgList.length"
          style="z-index: 99999999999999;"></imgViever>
        <previewPicture v-if="pdfUrl" :imgUrl="pdfUrl"></previewPicture>
      </div>
    </div>
    <!-- txt -->
    <iframe :src="txtUrl" width="100%" height="775px" v-if="itemList.DOC_FILE_TYPE == 'TXT'"></iframe>
    <!-- <div  v-if="itemList.DOC_FILE_TYPE == 'TXT'">{{ txtUrl }}</div> -->

    <!-- ofd shuke-->
    <!-- <shukeOfd v-if="itemList.isTypeShow" :infoItem="infoItem"></shukeOfd> -->
    <shukeOfd :ofdUrl="ofdUrl" :item="item" :borrowItemId="borrowItemId"
      v-if="itemList.DOC_FILE_TYPE == 'OFD' && ofdUrl && ofdType == 'SUWELL'"
      :style="istype == '1' ? 'height:750px' : 'height:800px'"></shukeOfd>

    <!-- ofd 友虹  -->
    <iframe v-if="itemList.DOC_FILE_TYPE == 'OFD' && ofdType == 'SC'" src="/SCOFDReader/v.html" style="width:100%"
      :style="istype == '1' ? 'height:750px' : 'height:800px'" ref="iFrame"></iframe>

    <!--ofd 书生 -->

    <shuShen :ofdUrl="ofdUrl" :borrowItemId="borrowItemId"
      v-if="itemList.DOC_FILE_TYPE == 'OFD' && ofdUrl && ofdType == 'SS'" style="width:100%"
      :style="istype == '1' ? 'height:750px' : 'height:800px'"></shuShen>

    <!--ofd 福昕 客户端 -->
    <foxit :ofdUrl="ofdUrl" v-if="itemList.DOC_FILE_TYPE == 'OFD' && ofdUrl && ofdType == 'FXK'" style="width:100%"
      :style="istype == '1' ? 'height:750px' : 'height:800px'"></foxit>
    <!--ofd 福昕 云阅读 -->
    <iframe v-if="itemList.DOC_FILE_TYPE == 'OFD' && ofdType == 'FXY'" style="width: 100%;" :src="ofdUrl"
      :style="istype == '1' ? 'height:750px' : 'height:800px'"></iframe>
    <!-- word -->
    <!-- <div v-if="docUrl=='1'"> -->
    <div class="scroll" :style="istype == '1' ? 'height:750px' : 'height:800px'"
      v-if="itemList.DOC_FILE_TYPE == 'DOC' || itemList.DOC_FILE_TYPE == 'DOCX'">
      <div v-if="docUrl == '1'" ref="file"></div>
    </div>
    <!-- </div> -->
    <!-- xls -->
    <div v-if="itemList.DOC_FILE_TYPE == 'XLS' || itemList.DOC_FILE_TYPE == 'XLSX'">

      <el-tabs v-model="activeName" type="border-card">
        <el-tab-pane v-for="(item, index) in excelSheet" :key="index" :label="item.name" :name="item.name">
          <div class="table-html-wrap scroll" :style="istype == '1' ? 'height:690px' : 'height: 730px'"
            v-html="item.innerHTML">
          </div>
        </el-tab-pane>
      </el-tabs>
      <!-- :page-sizes="[9, 18, 27, 36]" -->
      <el-pagination style="margin-top:10px;float:left" @current-change="changePage" :current-page="currentPage"
        :page-size="dataPerPage" :total="total" layout="total, prev, pager, next, jumper"></el-pagination>
    </div>
    <!-- mp4 -->
    <!-- controlslist="nodownload  nofullscreen noremoteplayback ”-->
    <div v-if="itemList.DOC_FILE_TYPE == 'MP4' && mp4Url.length > 0" style="width:620px;margin:16% auto 0">
      <video width="620" height="390" controls muted controlslist="nodownload ">
        <source :src="mp4Url" type="video/mp4">
        <source src="movie.ogg" type="video/ogg">
      </video>

    </div>

    <!-- mp3 -->
    <div v-if="itemList.DOC_FILE_TYPE == 'MP3' && mp3Url.length > 0" style="width:300px;margin:30% auto 0">
      <audio controls controlslist="nodownload ">
        <source :src="mp3Url" type="audio/ogg">
        <source :src="mp3Url" type="audio/mpeg">
      </audio>
    </div>
    <!-- jpg  png -->
    <div v-if='itemList.DOC_FILE_TYPE == "PNG" || itemList.DOC_FILE_TYPE == "JPG" || itemList.DOC_FILE_TYPE == "JPEG"'
      style="position: relative;overflow: hidden;" :style="istype == '1' ? 'height:740px' : 'height: 790px'">
      <previewPicture v-if="imgUrl" :imgUrl="imgUrl"></previewPicture>
    </div>
  </div>
</template>

<script>
import {sydm} from "@/api/archive/fileCollection/offlinReception.js";
import {pdfIsEncryption} from "@/api/cqbc/dataManage/yqDatamanageTree.js"
import pdfDemo from '@/components/componentsPdf/pdflib1.vue'
// 引入docx-preview插件
import { renderAsync } from "docx-preview";
//引入xlsx插件
import * as XLSX from 'xlsx';
// import '@/assets/styles/file.css'//xlsx样式
import previewPicture from '@/components/componentsImg/index.vue'
import axios from "axios";
import { getToken } from "@/utils/auth";
import imgViever from "@/components/ImagePreview/viewer.vue"
import shuShen from "@/components/sushen/index.vue"
import shukeOfd from '@/views/shukeOfd/index'
import foxit from '@/views/fuxinOfd/index'
// import { getDocument } from 'pdfjs-dist/build/pdf';
import { degrees, PDFDocument, rgb, StandardFonts } from 'pdf-lib';
export default {
  components: { pdfDemo, previewPicture, imgViever, shuShen, shukeOfd, foxit },
  props: ["item", "celldbData", "istype", 'source', 'borrowItemId'],
  watch: {
    item: {
      handler(valNew, valOld) {

        this.getConfigKey("OfdReadName").then(response => {
          // SC = 友虹 SUWELL = 数科  FXK = 福昕客户端  FXY = 福昕云阅读 SS = 书生
          this.ofdType = response.msg
          // console.log(this.ofdType,"watch-------------------------")
          if (!valNew.DOC_FILE_TYPE.match(/^([A-Z])+$/)) {
            // console.log(valNew.DOC_FILE_TYPE,"valNew.DOC_FILE_TYPE")
            valNew.DOC_FILE_TYPE = valNew.DOC_FILE_TYPE.toUpperCase()

          }
          this.itemList = valNew;

          console.log(valNew, "fjsdlkfjsdkljfklj")
          // 编研
          if (this.source == 'bianyan') {
            if (valNew.type == '1') { //编研资料预览
              // this.getdataTap(valNew)
            } else { //编研档案预览
              // this.getBydaTap(valNew)
            }
          } else if (this.source == 'bianyanfb') { //编研发布

            // this.getbyfbTap(valNew)
          } else {
            //  console.log(valNew.isShowjieyue, valNew.borrowId,"=====================================lalalallalalalallalalalal")
            // console.log(valNew.isShowjieyue == true, valNew.borrowId != undefined, valNew.DOC_FILE_TYPE == 'PDF')
            if (valNew.isShowjieyue == true && valNew.borrowId != undefined && (valNew.DOC_FILE_TYPE == 'PDF' || valNew.DOC_FILE_TYPE == 'OFD')) { // 借阅管理中授权后PDF预览
              //  console.log("--------------------------------------pdfofd")
              this.getYyTap(valNew)
            } else {
              this.getfileTap(valNew)
            }
          }
        });

      },
      immediate: true,
    }
  },

  data() {
    return {

      isText: "",
      itemList: {},
      pdfUrl: "",
      txtUrl: "",
      imgUrl: "",
      mp4Url: "",
      mp3Url: "",
      ofdUrl: "",
      xlsUrl: "",
      docUrl: "",
      isUrl: "", //判断显示图片还是pdf
      imgList: [],
      excelSheet: [],
      activeName: "",
      // 当前分页
      currentPage: 1,

      // 数据总数
      total: 0,

      dataPerPage: 50,
      startIndex: 0,
      endIndex: 0,
      tableData: [],
      // ofd类型
      ofdType: '',
    }
  },
  created() {
    // Vue.use(SCOFDReader);



  },
  mounted() {

  },
  methods: {


    blobToUint8Array(blob) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = event => {
          const arrayBuffer = event.target.result;
          const uint8Array = new Uint8Array(arrayBuffer);
          resolve(uint8Array);
        };
        reader.onerror = error => {
          reject(error);
        };
        reader.readAsArrayBuffer(blob);
      });
    },
    getBrowserVersion() {
      const userAgent = navigator.userAgent;
      const isChrome = userAgent.indexOf("Chrome") > -1;
      const isFirefox = userAgent.indexOf("Firefox") > -1;
      const isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") === -1;
      const isOpera = userAgent.indexOf("Opera") > -1;
      const isEdge = userAgent.indexOf("Edge") > -1;
      const isQiAnXin = userAgent.indexOf("QiAnXin") > -1; // 假设奇安信浏览器的用户代理中包含"QiAnXin"

      let version = "Unknown";

      if (isChrome || isQiAnXin) {
        const chromeMatch = userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);
        if (chromeMatch && chromeMatch.length > 2) {
          version = chromeMatch[2];
        }
      } else if (isFirefox) {
        const firefoxMatch = userAgent.match(/Firefox\/([0-9]+)\./);
        if (firefoxMatch && firefoxMatch.length > 1) {
          version = firefoxMatch[1];
        }
      } else if (isSafari) {
        const safariMatch = userAgent.match(/Version\/([0-9\.]+)\sSafari/);
        if (safariMatch && safariMatch.length > 1) {
          version = safariMatch[1];
        }
      } else if (isOpera) {
        const operaMatch = userAgent.match(/OPR\/([0-9]+)\./);
        if (operaMatch && operaMatch.length > 1) {
          version = operaMatch[1];
        }
      } else if (isEdge) {
        const edgeMatch = userAgent.match(/Edge\/([0-9]+)\./);
        if (edgeMatch && edgeMatch.length > 1) {
          version = edgeMatch[1];
        }
      }

      return version;
    },
    //===============================start   xls预览==================================
    // tableToHtml 方法用于将 Excel 工作表转换为 HTML 表格字符串，并将其存储在 excelSheet 数组中的对象中。每个对象包含工作表的名称和对应的 HTML 字符串。
    tableToHtml(workbook) {
      var that = this;
      this.excelSheet = [];
      const sheetList = workbook.SheetNames.filter((v) => v.indexOf("数据源") === -1);
      this.activeName = sheetList[0];
      sheetList.forEach((sheet) => {
        const worksheet = workbook.Sheets[sheet];
        if (worksheet) {
          const range = XLSX.utils.decode_range(worksheet["!ref"]);
          range.e.r = Math.min(range.e.r, this.dataPerPage - 1); // Limiting to dataPerPage rows only for preview
          worksheet["!ref"] = XLSX.utils.encode_range(range);
          const innerHTML = XLSX.utils.sheet_to_html(worksheet);
          // console.log(this.generateTableHTML(this.tableDataPage),"skldfjklsdj")

          this.excelSheet.push({
            name: sheet,
            innerHTML: innerHTML,
          });
          this.$modal.closeLoading();

        } else {
          this.excelSheet.push({
            name: sheet,
            innerHTML: "暂无数据",
          });
        }
      });

      // Calculate start and end indexes for pagination
      that.startIndex = 0;
      that.endIndex = Math.min(that.tableData.length, this.dataPerPage) - 1;
      that.tableDataPage = that.tableData.slice(that.startIndex, that.endIndex + 1);
    },

    //在 readWorkbookFromRemoteFile 方法中，您首先使用 FileReader 读取 Excel 文件的二进制数据。
    //然后使用 XLSX.read 方法将二进制数据解析为工作簿对象 workbook。接下来，
    //您使用 XLSX.utils.sheet_to_json 方法将工作表的数据转换为 JSON 格式，并将其存储在 tableData 数组中。
    readWorkbookFromRemoteFile(file) {
      const that = this;
      let f = file;
      let reader = new FileReader();
      reader.onload = function (e) {
        var data = new Uint8Array(e.target.result);
        var workbook = XLSX.read(data, { type: "array" });

        if (workbook) {

        }

        var outdata = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
        that.tableData = outdata;
        that.total = outdata.length;
        console.log(that.tableData, "))))))))))))))))")
        that.handlePageChange(that.currentPage); // Update the current page data
        that.tableToHtml(workbook);

      };
      reader.readAsArrayBuffer(f);
    },

    //获取每页加载的数据
    handlePageChange(page) {
      this.excelSheet = [];
      this.currentPage = page;
      this.startIndex = (page - 1) * this.dataPerPage;
      this.endIndex = Math.min(this.startIndex + this.dataPerPage - 1, this.tableData.length - 1);
      this.tableDataPage = this.tableData.slice(this.startIndex, this.endIndex + 1);
    },
    // 定义一个函数，用于生成表格的 HTML
    generateTableHTML(data) {
      let html = '<html><head><meta charset="utf-8"/><title>SheetJS Table Export</title></head><body><table>';

      // 生成表头
      html += '<thead><tr>';
      for (let key in data[0]) {
        html += `<th>${key}</th>`;
      }
      html += '</tr></thead>';

      // 生成表格内容
      html += '<tbody>';
      for (let row of data) {
        html += '<tr>';
        for (let key in row) {
          html += `<td>${row[key]}</td>`;
        }
        html += '</tr>';
      }
      html += '</tbody>';

      html += '</table></body></html>';
      return html;
    },


    //  changePage 方法来更新当前页的数据。然后，您调用了 tableToHtml 方法来生成 HTML 表格字符串，并将它们存储在 excelSheet 数组中的对象中。
    changePage(page) {
      var that = this;
      this.excelSheet = [];
      // this.$modal.loading("正在预览文件，请稍候...")
      this.currentPage = page;
      this.handlePageChange(page);


      this.excelSheet.push({
        name: this.activeName,
        innerHTML: this.generateTableHTML(this.tableDataPage),

      });
      // console.log(this.excelSheet,this.excelSheet!=null||this.excelSheet!=undefined"show______")
      // if(this.excelSheet!=null||this.excelSheet!=undefined){

      // }
      // let reader = new FileReader();
      // reader.onload = function (e) {
      //   var data = new Uint8Array(e.target.result);
      //   var workbook = XLSX.read(data, { type: "array" });

      //   if (workbook) {
      //     that.$modal.closeLoading();
      //   }

      //   var outdata = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
      //   that.tableData = outdata;
      //   that.total = outdata.length;
      //   that.handlePageChange(that.currentPage); // Update the current page data
      // //  that.tableToHtml(workbook);
      // };
      // reader.readAsArrayBuffer(this.xlsUrl);

    },
    //===============================end .xls 文件预览===================================================

    runAsync(blob) {
      var p = new Promise(function (resolve, reject) {
        //做一些异步操作
        // setTimeout(function () {
        // 创建一个 FileReader 对象
        var reader = new FileReader();
        // 将 Blob 对象转换为数组缓冲区
        reader.onloadend = function (event) {
          const existingPdfBytes = event.target.result;
          var pdfDoc = PDFDocument.load(existingPdfBytes)

          resolve(pdfDoc);
        }
        reader.readAsArrayBuffer(blob);
        // }, 1000);
      }).catch((e) => { });

      return p;

    },

    runAsyncCanvas(pdfDoc, imgBlob, pages) {
      var p = new Promise(function (resolve, reject) {
        //做一些异步操作
        // setTimeout(function () {
        // 创建一个 FileReader 对象
        var reader = new FileReader();
        // 将 Blob 对象转换为数组缓冲区
        reader.onload = function (event) {
          const arrayBuffer = event.target.result;
          var pngImage = pdfDoc.embedPng(arrayBuffer)
          resolve(pngImage);
        }
        reader.readAsArrayBuffer(imgBlob);
        // }, 100);
      }).catch((e) => {

      });
      return p;
    },

    getfileTap(item) {
      var that = this;
      this.pdfUrl = "";
      this.txtUrl = "";
      this.imgUrl = "";
      this.mp4Url = "";
      this.mp3Url = "";
      this.ofdUrl = "";
      this.docUrl = "";
      this.excelSheet = [];
      this.activeName = "";
      // 当前分页
      this.currentPage = 1;
      this.dataPerPage = 50,
        this.startIndex = 0,
        this.endIndex = 0,
        // 数据总数
        this.total = 0;
      var arr = ['PNG', 'JPG', 'JPEG', 'TXT', 'DOCX', 'XLSX', 'XLS', 'PDF', 'OFD', 'MP3', 'MP4']
      if (!arr.includes(item.DOC_FILE_TYPE)) {
        this.$modal.msgWarning('该文件格式不支持预览')
        this.pdfUrl = "";
        this.txtUrl = "";
        this.imgUrl = "";
        this.mp4Url = "";
        this.mp3Url = "";
        this.ofdUrl = "";
        this.docUrl = "";
        return
      }
      if (item.DOC_FILE_TYPE == "DOCX" || item.DOC_FILE_TYPE == "DOC") {
        this.docUrl = 1;
        axios({
          method: 'POST',
          url: process.env.VUE_APP_BASE_API + `/cqbc/detail/view`,
          params: {
            docId: item.DOC_ID,
            categoryId: item.categoryId
          },
          headers: {
            Authorization: "Bearer " + getToken()
          },
          responseType: 'arraybuffer' // 更改responseType类型为 arraybuffer
        }).then(res => {
          // console.log(res.data, this.$refs.file, "+++++++++111111111+++++++++++")
          this.$nextTick(() => {
            renderAsync(res.data, this.$refs.file).then(x => console.log(
              "docx: finished", x))
          })


        }).catch(err => {
          console.log(err)
        })
      } else if (item.DOC_FILE_TYPE == "PDF") {
        // this.$modal.loading("正在预览文件，请稍候...")
        this.isText = "正在预览文件，请稍候..."
        // cutBigPdf({
        //   docId: item.DOC_ID,
        //   categoryId: item.categoryId
        // }).then(res => {
          // if (res.code == "200") { //>1M显示图片
          //   if (res.data.imgList.length <= 0) {
          //     this.isUrl = false
          //     this.isText = ""
          //     this.$alert('文件已损坏', '', {
          //       confirmButtonText: '确定',
          //       callback: action => {

          //       }
          //     });
          //     return
          //   }
          //   this.isUrl = false
          //   // this.$modal.closeLoading()
          //   this.isText = "";
          //   this.imgList = res.data.imgList
          //   axios({
          //     method: 'POST',
          //     url: process.env.VUE_APP_BASE_API + `/archive/detail/viewImg`,
          //     params: {
          //       file: res.data.bigImg
          //     },
          //     headers: {
          //       Authorization: "Bearer " + getToken()
          //     },
          //     responseType: 'blob' // 更改responseType类型为 blob
          //   }).then(res => {

          //     const blob = new Blob([res.data], {
          //       type: "image/jpeg",
          //     })
          //     this.pdfUrl = window.URL.createObjectURL(blob)
          //   }).catch(err => {
          //     console.log(err, "====")

          //   })
          // } else if (res.code == "-1") {  //<1M显示pdf
            this.isUrl = true
            axios({
              method: 'POST',
              url: process.env.VUE_APP_BASE_API + `/cqbc/detail/view`,
              params: {
                docId: item.DOC_ID,
                categoryId: item.categoryId
              },
              headers: {
                Authorization: "Bearer " + getToken()
              },
              responseType: 'blob' // 更改responseType类型为 blob
            }).then(res => {
              const blob = new Blob([res.data], { type: 'application/pdf;charset-UTF-8' });
              sydm({
                sydm: "yulan"
              }).then(res => {
                pdfIsEncryption({

                  docId: this.item.DOC_ID,
                  categoryId: this.item.categoryId
                }).then(response => {
                  that.isydm = response.data;
                  that.text = res.data.synr
                  console.log(res.data.synr)
                  if (res.data.synr != "" && !response.data) { //需要水印
                    // labels是要显示的水印文字，垂直排列
                    let labels = [];
                    labels.push(that.text);
                    that.runAsync(blob).then(pdfDoc => {

                      const pages = pdfDoc.getPages();
                      const size = pages[0].getSize();
                      let pageWidth = size.width
                      let pageHeight = size.height


                      let canvas = document.createElement('canvas'); //新建水印canvas容器
                      const context = canvas.getContext('2d');
                      let canvasWidth = canvas.width = pageWidth;
                      let canvasHeight = canvas.height = pageHeight;
                      context.font = res.data.fontsize + 'px Arial'; // 设置文字的大小
                      context.fillStyle = res.data.color;// 设置文字的颜色
                      context.textAlign = 'center'; // 设置文本居中对齐
                      context.textBaseline = 'middle'; // 设置文本基线为中间
                      let textWidthNum = Math.max(...labels.map(item => context.measureText(item).width));// 获取文本的最大长度
                      // console.log(pages, size, canvasWidth, canvasHeight, "textWidthNum=", textWidthNum, "888888888888888888888888888")
                      // 需要旋转的角度（以度为单位）
                      var angleInDegrees = 0;
                      var lineHeight = 0; // 行高
                      var lineSpacing = 0; // 行间距
                      var columnSpacing = 0; // 列间距
                      // console.log(pageHeight, pageWidth, pageHeight < pageWidth, "-------------------00")
                      if (pageHeight < pageWidth) {
                        angleInDegrees = -15;
                        lineHeight = 50; // 行高
                        lineSpacing = 50; // 行间距
                        columnSpacing = textWidthNum / 2; // 列间距
                      } else {
                        angleInDegrees = -30;
                        lineHeight = 50; // 行高
                        lineSpacing = 130; // 行间距
                        columnSpacing = textWidthNum / 4; // 列间距
                      }
                      const angleInRadians = angleInDegrees * (Math.PI / 180);

                      // 计算canvas的中心点
                      // const centerX = canvasWidth / 3;

                      const centerX = -(canvasHeight / 3);
                      const centerY = canvasHeight / 3;
                      // const centerY = canvasHeight / 3;


                      console.log(columnSpacing, textWidthNum + columnSpacing, pageWidth, "000000", (canvasHeight / 3))
                      // 文本行 列
                      var row = Math.round(pageHeight / (lineHeight + lineSpacing)) * 10//4行
                      var col = Math.round(pageWidth / (textWidthNum + columnSpacing)) * 10;//4列

                      // console.log(Math.round(pageHeight/(lineHeight+lineSpacing)),"行")
                      // 移动到旋转中心并旋转
                      context.translate(centerX, centerY);
                      context.rotate(angleInRadians);
                      let maxWidth = 0;
                      //  如果文本不一样的计算规则： 计算每行文本的宽度和高度
                      const metrics = context.measureText(that.text);
                      maxWidth = Math.max(maxWidth, metrics.width);
                      console.log(row, col, "2")
                      const textWidth = maxWidth + columnSpacing * (col - 1);
                      const textHeight = lineHeight * row + lineSpacing * (row - 1);

                      //console.log(textWidth,textHeight)
                      // 计算文本的起始坐标

                      const offsetX = -textWidth / 2;

                      const offsetY = textHeight / 2;
                      console.log(row, col, "3")
                      //console.log("canvasWidth=", canvasWidth, "canvasHeight=", canvasHeight, centerX, centerY, "offsetX=" + offsetX, "offsetY=", offsetY)
                      // 绘制文本网格
                      context.fillStyle = res.data.color; // 字体颜色
                      for (let i = 0; i < row; i++) {

                        for (let j = 0; j < col; j++) {

                          const x = offsetX + j * (maxWidth + columnSpacing);

                          const y = offsetY - i * (lineHeight + lineSpacing);


                          labels.forEach(item => {
                            context.fillText(item, x, y);
                          })
                          // console.log("i=" + x + ",j=" + y)
                        }

                      }
                      console.log(row, col, "4")

                      // 恢复之前保存的状态
                      context.restore();
                      // 图片的base64编码路径
                      let dataUrl = canvas.toDataURL('image/png');
                      console.log(dataUrl, "-----------------------------haoden")

                      // 使用Xhr请求获取图片Blob
                      let xhr = new XMLHttpRequest();
                      xhr.open("get", dataUrl, true);
                      xhr.responseType = "blob";
                      xhr.onload = res => {

                        const imgBlob = res.target.response
                        console.log("imgBlob", imgBlob)

                        //兼容低版本的谷歌浏览器
                        this.runAsyncCanvas(pdfDoc, imgBlob, pages).then(async pngImage => {

                          for (let i = 0; i < pages.length; i++) {
                            pages[i].drawImage(pngImage)
                          }

                          const pdfBytes = await pdfDoc.save()
                          console.log("pdfbutes=", pdfBytes)
                          var pdfurl = URL.createObjectURL(new Blob([pdfBytes], { type: 'application/pdf;charset=utf-8' }))

                          if (this.getBrowserVersion() <= 79) {
                            this.pdfUrl = pdfurl + "#toolbar=0&navpanes=0&scrollbar=0";
                            this.isText = "";
                          } else {
                            this.pdfUrl = '/pdfjs/web/viewer.html?file=' + pdfurl
                            this.isText = "";
                          }
                          // console.log(href,"sdklfjsdkljf")
                          // this.pdfUrl = window.URL.createObjectURL(blob)
                        })

                      }
                      xhr.send();
                    });
                  } else {//不需要水印
                    var pdfurl = window.URL.createObjectURL(blob)
                    if (this.getBrowserVersion() <= 79) {

                      this.pdfUrl = pdfurl + "#toolbar=0&navpanes=0&scrollbar=0";
                      this.isText = "";
                    } else {
                      this.pdfUrl = '/pdfjs/web/viewer.html?file=' + pdfurl
                      this.isText = "";
                    }
                  }

                })

              })




            }).catch(err => {
              console.log(err, "-------")
            })
          // }
        // }).catch(res => {
        //   this.$modal.closeLoading()
        // })

      } else if (item.DOC_FILE_TYPE == "OFD") {
        axios({
          method: 'POST',
          url: process.env.VUE_APP_BASE_API + `/cqbc/detail/getOfdFile`,
          params: {
            docId: item.DOC_ID,
            categoryId: item.categoryId
          },
          headers: {
            Authorization: "Bearer " + getToken()
          },
        }).then(res => {
          // const blob = new Blob([res.data.msg], { type: 'application/ofd;charset-UTF-8' });
          // this.ofdUrl =  window.URL.createObjectURL(blob)
          if (this.ofdType == "FXY") {
            // console.log(window.location.protocol + ',' + window.location.host+','+process.env.VUE_APP_BASE_API,res.data.msg)
            // this.ofdUrl = window.location.protocol + '//' + window.location.host + process.env.VUE_APP_BASE_API + `/archive/detail/viewOfd?token=` + res.data.msg
            var token = res.data.msg
            axios({
              method: 'GET',
              url: process.env.VUE_APP_BASE_API + `/cqbc/detail/cloud/reading`,
              params: {
                token: token,
                sydm: "yulan"
              },
              headers: {
                Authorization: "Bearer " + getToken()
              },
            }).then(response => {
              console.log(response)
              console.log(response.data)
              this.ofdUrl = response.data
            })
          } else if (this.ofdType == "SC") {   //这一块是友虹的
            axios({
              method: 'POST',
              url: process.env.VUE_APP_BASE_API + `/cqbc/detail/view`,
              params: {
                docId: item.DOC_ID,
                categoryId: item.categoryId
              },
              headers: {
                Authorization: "Bearer " + getToken()
              },
              responseType: 'blob' // 更改responseType类型为 blob
            }).then(res => {
              setTimeout(() => {
                //友虹
                var iframeWin = this.$refs.iFrame.contentWindow;
                iframeWin.postMessage({ blob: res.data }, "*");
              }, 600)


            }).catch(err => {
              console.log(err)
            })
          } else {
            this.ofdUrl = res.data.msg
          }

        }).catch(err => {
          console.log(err)
        })






      } else if (item.DOC_FILE_TYPE == "TXT") {
        axios({
          method: 'POST',
          url: process.env.VUE_APP_BASE_API + `/cqbc/detail/view`,
          params: {
            docId: item.DOC_ID,
            categoryId: item.categoryId
          },
          headers: {
            Authorization: "Bearer " + getToken()
          },
          responseType: 'blob' // 更改responseType类型为 blob
        }).then(res => {
          const blob = new window.Blob([res.data], {
            type: res.headers["content-type"],
          })
          // console.log(res.data)
          this.txtUrl = URL.createObjectURL(blob)
          // const iconv = require('iconv-lite');
          // // 处理文件流

          // const reader = new FileReader();

          // reader.onload = (e) => {
          //   const arrayBuffer = e.target.result;
          //   const buffer = Buffer.from(arrayBuffer);
          //   const strUTF8 = iconv.decode(buffer, 'gbk');
          //   console.log(strUTF8); // 输出转换后的UTF-8字符串
          //   this.txtUrl=strUTF8
          // };

          // reader.readAsArrayBuffer(res.data);



        }).catch(err => {
          console.log(err)
        })
      } else if (item.DOC_FILE_TYPE == "XLSX" || item.DOC_FILE_TYPE == "XLS") {
        this.$modal.loading("正在预览文件，请稍候...")


        async function view() {

          const response = await axios({
            method: 'POST',
            url: process.env.VUE_APP_BASE_API + `/cqbc/detail/view`,
            params: {
              docId: item.DOC_ID,
              categoryId: item.categoryId
            },
            headers: {
              Authorization: "Bearer " + getToken()
            },
            responseType: 'blob' // 更改responseType类型为 blob
          })
          return response;
          // console.log(response, "liuhaiorng")
          // return
          // if (res.data) {
          //   that.$modal.closeLoading();
          //   let file = new File([res.data], 'demo.ofd')
          //   that.readWorkbookFromRemoteFile(file)
          // }

        }

        view().then(res => {
          // var url = URL.createObjectURL(res.data)
          that.xlsUrl = res.data
          that.readWorkbookFromRemoteFile(res.data)

        })
        // axios({
        //   method: 'POST',
        //   url: process.env.VUE_APP_BASE_API + `/archive/detail/view`,
        //   params: {
        //     docId: item.DOC_ID,
        //     categoryId: item.categoryId
        //   },
        //   headers: {
        //     Authorization: "Bearer " + getToken()
        //   },
        //   responseType: 'blob' // 更改responseType类型为 blob
        // }).then( res => {

        //   this.$modal.closeLoading();
        //   let file = new File([res.data], 'demo.ofd')
        //   this.readWorkbookFromRemoteFile(file)

        // }).catch(err => {
        //   console.log(err)
        // })
      } else if (item.DOC_FILE_TYPE == "PNG" || item.DOC_FILE_TYPE == "JPG" || item.DOC_FILE_TYPE == "JPEG") {
        axios({
          method: 'POST',
          url: process.env.VUE_APP_BASE_API + `/cqbc/detail/view`,
          params: {
            docId: item.DOC_ID,
            categoryId: item.categoryId
          },
          headers: {
            Authorization: "Bearer " + getToken()
          },
          responseType: 'blob' // 更改responseType类型为 blob
        }).then(res => {
          console.log(res, "tupian")
          const blob = new Blob([res.data], {
            type: "image/jpeg",
          })
          this.imgUrl = window.URL.createObjectURL(blob)
        }).catch(err => {
          console.log(err)
        })
      } else if (item.DOC_FILE_TYPE == "MP4") {
        axios({
          method: 'POST',
          url: process.env.VUE_APP_BASE_API + `/cqbc/detail/view`,
          params: {
            docId: item.DOC_ID,
            categoryId: item.categoryId
          },
          headers: {
            Authorization: "Bearer " + getToken()
          },
          responseType: 'blob' // 更改responseType类型为 blob
        }).then(res => {
          const blob = new Blob([res.data], {
            type: "video/mp4",
          })
          this.$nextTick(res => {
            this.mp4Url = window.URL.createObjectURL(blob)
          })

        }).catch(err => {
          console.log(err)
        })
      } else if (item.DOC_FILE_TYPE == "MP3") {
        axios({
          method: 'POST',
          url: process.env.VUE_APP_BASE_API + `/cqbc/detail/view`,
          params: {
            docId: item.DOC_ID,
            categoryId: item.categoryId
          },
          headers: {
            Authorization: "Bearer " + getToken()
          },
          responseType: 'blob' // 更改responseType类型为 blob
        }).then(res => {
          const blob = new Blob([res.data], {
            type: "audio/mpeg",
          })

          this.$nextTick(res => {
            this.mp3Url = window.URL.createObjectURL(blob)
            var audio = new Audio('mp3/music.mp3');
          })

        }).catch(err => {
          console.log(err)
        })
      }

    },

   



 
  }
}
</script>

<style lang="less" scoped>
ul,
li,
p,
div {
  padding: 0;
  margin: 0;
}

/deep/.el-card__body {
  padding: 0;
}

/deep/.el-dialog {
  margin: 25px auto 0 !important;
}


/deep/.el-tabs--border-card>.el-tabs__content {
  padding: 0 !important;
}


.el-col-17 {
  width: 74.83333% !important;
}

.ajinfo {
  position: absolute;
  top: 16px;
  right: 76px;
  color: #fff;
  font-size: 18px;
}

.dataList li {
  font-size: 16px;
  line-height: 50px;
  border-bottom: 1px dashed #cccccc4d;
}

.dataList li p {
  width: 302px;
}

.dataList li label {
  font-weight: bold;
  text-align: right;
  margin-right: 10px;
}

.scroll {
  overflow-y: scroll;
}

.info-scroll {
  overflow-y: scroll;
  height: 900px;
}

.tablist-scroll {
  overflow-y: scroll;
  height: 486px;
}

.box-card1jian {
  height: 526px;
}

.box-card2jian {
  height: 300px;
}

.itemList-scroll {
  overflow-y: scroll;
  height: 256px;

}

.box-cardjian {
  height: 837px;
}





.conterScroll-wj {
  overflow-y: scroll;
  height: 690px;
}

.conterwordScroll {
  overflow-y: scroll;
  height: 800px;
}


.el-dialog {
  margin-bottom: 0 !important;
}

.popup-main .el-tabs__item {
  height: 69px !important;
  line-height: 69px !important;
  font-size: 17px !important;
}

.tablistClass {
  padding: 0px 15px 10px;
}

.tablistClass li {
  height: 40px;
  line-height: 40px;
  font-size: 16px;

}

.chiderAvtia {
  border-bottom: 1px solid #409EFF;
  color: #409EFF;
}



// ofd  显示样式
#divId>div {
  margin: 0 auto;
}


// xls  样式
.table-html-wrap /deep/ table {

  border-collapse: collapse;

}

/deep/.table-html-wrap table {
  border-collapse: collapse;
  vertical-align: top;
  border-style: none;
}

.table-html-wrap /deep/ table td {
  border: 1px solid #ccc;
  min-width: 50px;
  height: 20px;
}

.table-html-wrap /deep/ table th {
  border: 1px solid #ccc;
  min-width: 50px;
  height: 20px;
}

// -----------------------------------
.headerInfoButton {
  position: absolute;
  top: 16px;
  right: 60px;
}

::v-deep .el-dialog__body {
  padding: 10px 20px 25px !important;
}

.margin_t {
  margin-top: 10px;
}

.text-ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}

.flex-row {
  display: flex;
  flex-direction: row;
}

.flex-row-bowtte {
  display: flex;
  flex-direction: row;
  justify-content: space-between
}

.itemList {
  padding: 10px 15px 10px;
}

.itemList p {
  line-height: 38px;
  display: block;
}
</style>
